import axios from "axios";
import Vue from "vue";
let vm = new Vue();
//设置请求拦截器
axios.interceptors.request.use(
  function(config) {
    //判断如果存在token
    if (localStorage.getItem("token")) {
      config.headers.common["token"] = localStorage.getItem("token");
      return config;
    } else {
      return config;
    }
  },
  function(error) {
    return Promise.reject(error);
  }
);
//设置响应拦截器
axios.interceptors.response.use(
  (response) => {
    let statusCode = response.data.code;
    let info = response.data.msg;
    //token过期处理
    //用户被删除,清空缓存,并刷新页面
    //20004 用户不存在，70006 token无效  20007用户授权异常
    //10012 加速币不足单独操作
    let isFirstExpire = localStorage.getItem("isFirstExpire");
    if (statusCode != 0) {
      if (info == "token已过期" && isFirstExpire == "false") {
        localStorage.setItem("isFirstExpire", true);
        reLogin();
      } else if (
        statusCode == 20004 ||
        statusCode == 70006 ||
        statusCode == 20007
      ) {
        vm.$alert(`${info}`, {
          confirmButtonText: "确定",
          callback: (action) => {
            localStorage.clear();
            window.location.reload();
          },
        });
      } else if (statusCode == 10012) {
      } else {
        vm.$message.warning(`${info}`);
      }
    }
    return response;
  },
  (error) => {
    return Promise.reject(error);
  }
);
//重新登录
function reLogin() {
  vm.$alert("会话过期请重新登录", {
    confirmButtonText: "确定",
    callback: (action) => {
      localStorage.clear();
      window.location.reload();
    },
  });
}
//token续期操作
function refreshToken() {
  let token = localStorage.getItem("token");
  if (token) {
    axios.get(`/laiwen/token/frontend/refresh?token=${token}`).then((res) => {
      localStorage.setItem("token", res.data.token);
    });
  }
}
//封装get
let baseUrl = `https://api.laismell.com`;
export function fetch(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios
      .get(`${baseUrl}${url}`, {
        params: params,
      })
      .then((response) => {
        // if(response.data.message === '无效token'){
        //   alert('无效token')
        //  }
        resolve(response.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

//封装post
export function post(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios
      .post(`${baseUrl}${url}`, data, {
        headers: { "Content-Type": "application/json" },
      })
      .then(
        (res) => {
          resolve(res.data);
        },
        (err) => {
          reject(err);
        }
      );
  });
}
